package Controller

import (
	"back_go/DAO/gorm"
	"back_go/DAO/gorm/GormModel"
	"back_go/Response"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"gorm.io/gorm/clause"
	"log"
	"math"
	"net/http"
	"strconv"
	"time"
)

// GetHotSearchPage 获取热搜分页
/*
 current: 当前页码，默认为1
 size: 分页大小，默认为10
 status: 状态，0为禁用，1为启用，默认为空，不区分状态
 return: 热搜分页信息
*/
func GetHotSearchPage(c *gin.Context) {
	var db = gorm.Db
	currentStr := c.Query("current")
	sizeStr := c.Query("size")
	statusStr := c.Query("status")
	content := c.Query("content") // 新增 content 参数

	var page, size int
	var err error
	if page, err = strconv.Atoi(currentStr); err != nil || page < 1 {
		page = 1
	}
	if size, err = strconv.Atoi(sizeStr); err != nil || size < 1 {
		size = 10
	}
	offset := (page - 1) * size

	// 构建查询条件
	query := db.Table("tz_hot_search")
	if statusStr != "" {
		status, err := strconv.Atoi(statusStr)
		if err == nil {
			query = query.Where("status = ?", status)
		}
	}
	if content != "" {
		query = query.Where("content LIKE ?", "%"+content+"%") // 添加 content 查询条件
	}

	// 执行查询并获取结果
	var hotSearches []GormModel.TzHotSearch
	err = query.Order(clause.OrderByColumn{Column: clause.Column{Name: "rec_date"}, Desc: true}).Offset(offset).Limit(size).Find(&hotSearches).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 计算总数
	var count int64
	err = query.Count(&count).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 构造响应
	c.JSON(http.StatusOK, gin.H{
		"code": "00000",
		"data": gin.H{
			"current": page,
			"total":   count,
			"size":    size,
			"records": hotSearches,
			"pages":   int(math.Ceil(float64(count) / float64(size))),
		},
		"msg":     nil,
		"success": true,
	})
}

// GetHotSearchById 通过id获取热搜信息
/*
  参数：
  	id: 热搜id
    return: 热搜信息
*/
func GetHotSearchById(c *gin.Context) {
	var db = gorm.Db
	id := c.Param("id")

	var hotSearch GormModel.TzHotSearch
	result := db.Table("tz_hot_search").First(&hotSearch, "hot_search_id = ?", id)

	if result.Error != nil {
		log.Printf("查询热搜失败: %v", result.Error)
		c.JSON(http.StatusOK, Response.ResponseBody{
			Code:      "A00005",
			Data:      nil,
			Msg:       "服务器出了问题",
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
		})
		return
	}

	if result.RowsAffected == 0 {
		c.JSON(http.StatusOK, Response.ResponseBody{
			Code:      "A00005",
			Data:      nil,
			Msg:       "热搜不存在",
			Version:   "1.0",
			Timestamp: time.Now().Unix(),
		})
		return
	}

	c.JSON(http.StatusOK, Response.ResponseBody{
		Code:      "00000",
		Data:      hotSearch,
		Msg:       nil,
		Success:   true,
		Fail:      false,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
	})
}

// DeleteHotSearchById 批量删除热搜信息
/*
   参数：
   	ids: 热搜id列表
    return: 200 状态码
*/
func DeleteHotSearchById(c *gin.Context) {
	var db = gorm.Db
	var ids []int64
	// 从请求参数中获取id列表
	if err := c.ShouldBindJSON(&ids); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了问题",
			"data":    nil,
			"success": false,
		})
		return
	}
	if len(ids) == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}
	tx := db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}
	for _, id := range ids {
		var hotSearch GormModel.TzHotSearch
		result := tx.Table("tz_hot_search").Delete(&hotSearch, "hot_search_id = ?", id)
		if result.Error != nil {
			tx.Rollback()
			c.JSON(http.StatusOK, gin.H{
				"code":    "A00005",
				"msg":     "服务器出了点小差",
				"data":    nil,
				"success": false,
			})
			return
		}
	}
	tx.Commit()
	c.JSON(http.StatusOK, gin.H{
		"code":    "00000",
		"msg":     "删除成功",
		"data":    nil,
		"success": true,
	})
}

type HotSearchRequest struct {
	HotSearchId int64  `json:"hotSearchId"`
	ShopId      int64  `json:"shopId"`
	Title       string `json:"title"`
	Content     string `json:"content"`
	Seq         *int   `json:"seq"`
	Status      int8   `json:"status"`
}

// SaveHotSearch 新增热搜信息
/*
  参数：
  	hotSearch: 热搜信息
    return: 200 状态码
*/

func SaveHotSearch(c *gin.Context) {
	var hotSearchRequest HotSearchRequest
	if err := c.ShouldBindJSON(&hotSearchRequest); err != nil {
		log.Printf("参数解析错误: %v", err)
		c.JSON(http.StatusOK, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了问题",
			"data":    nil,
			"success": false,
		})
		return
	}

	var db = gorm.Db
	tx := db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			log.Printf("事务回滚: %v", r)
		}
	}()

	if err := tx.Error; err != nil {
		log.Printf("数据库连接错误: %v", err)
		c.JSON(http.StatusOK, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}
	var hotSearch GormModel.TzHotSearch
	_ = copier.Copy(&hotSearch, &hotSearchRequest)
	// 设置录入时间
	now := time.Now()
	hotSearch.RecDate = &now
	//设置店铺id
	hotSearch.ShopId = 1
	// 创建热搜信息
	if err := tx.Table("tz_hot_search").Create(&hotSearch).Error; err != nil {
		tx.Rollback()
		log.Printf("创建热搜信息失败: %v", err)
		c.JSON(http.StatusOK, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}

	tx.Commit()
	c.JSON(http.StatusOK, gin.H{
		"code":    "00000",
		"msg":     "ok",
		"data":    nil,
		"success": true,
	})
}

// UpdateHotSearch 更新热搜信息
/*
  参数：
  	hotSearch: 热搜信息
    return: 200 状态码
*/
func UpdateHotSearch(c *gin.Context) {
	var db = gorm.Db
	var hotSearchRequest HotSearchRequest
	if err := c.ShouldBindJSON(&hotSearchRequest); err != nil {
		log.Printf("参数解析错误: %v", err)
		c.JSON(http.StatusOK, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了问题",
			"data":    nil,
			"success": false,
		})
	}
	//打印出获取的结构体
	log.Printf("更新热搜信息: %+v", hotSearchRequest)
	tx := db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			log.Printf("事务回滚: %v", r)
		}
	}()
	if err := tx.Error; err != nil {
		log.Printf("数据库连接错误: %v", err)
		c.JSON(http.StatusOK, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
	}
	var hotSearch GormModel.TzHotSearch
	_ = copier.Copy(&hotSearch, &hotSearchRequest)
	//录入时间也更改
	now := time.Now()
	hotSearch.RecDate = &now
	//设置店铺id
	hotSearch.ShopId = 1
	// 使用 map 强制更新所有字段
	updateData := map[string]interface{}{
		"shop_id":  hotSearch.ShopId,
		"content":  hotSearch.Content,
		"rec_date": hotSearch.RecDate,
		"seq":      hotSearch.Seq,
		"status":   hotSearch.Status, // 确保包含 status 字段
		"title":    hotSearch.Title,
	}

	result := tx.Table("tz_hot_search").Where("hot_search_id = ?", hotSearch.HotSearchId).Updates(updateData)
	if result.Error != nil {
		tx.Rollback()
		log.Printf("更新热搜信息失败: %v", result.Error)
		c.JSON(http.StatusOK, gin.H{
			"code":    "A00005",
			"msg":     "服务器出了点小差",
			"data":    nil,
			"success": false,
		})
		return
	}
	tx.Commit()
	c.JSON(http.StatusOK, gin.H{
		"code":    "00000",
		"msg":     "ok",
		"data":    nil,
		"success": true,
		"sign":    "",
		"version": "v1.0",
	})
}
